<?php

namespace App\Exceptions;

use App\Http\Controllers\API\StatusController;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Artisan;
use JetBrains\PhpStorm\NoReturn;
use Symfony\Component\ErrorHandler\Error\FatalError;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {

        });
    }

    /**
     *自定义响应返回
     *
     * @throws Throwable
     */
    #[NoReturn] public function render($request, Exception|Throwable $e)#统一错误响应
    {
        /*数据库错误*/
        if ($e instanceof QueryException) {
            try{
                $error = explode('error:', $e->getMessage())[1];

            }catch (Throwable $error1){
                return Fail('数据库错误:'.$e->errorInfo[2],[
                    'Error'=>$e->errorInfo[2],
                    'ErrorSql:'=> $e->getMessage(),
                    'line'=>$e->getLine()
                ]);
            }
                function xt($er, $tx): bool
                {
                    return (str_contains($er, $tx)); // 使用 !== false 而不是 !== null
                }
                $start = '';
                if (xt($error, 'insert')) {
                    $start = '创建新数据时发生了';
                } elseif (xt($error, 'update')) {
                    $start = '更新数据时发生了';
                } elseif (xt($error, 'delete')) {
                    $start = '删除数据时发生了';
                } else {
                    $start = '发生了数据库操作错误';
                }
                return Fail('数据库错误'.$start,[
                    'Error'=>"【数据库错误】 ".explode('error:',$e->getMessage())[1],
                    'ErrorSql:'=> substr(explode('SQL:',$e->getMessage())[1], 0, -1),
                    'line'=>$e->getLine()
                ]);
        }
        /*用户登录错误*/
        if ($e instanceof AuthenticationException) {
            // 处理 Unauthenticated 异常的逻辑
            $lang = getLang();
            $message = [
                'ug'=>'ئەزالار سالاھىيەت كودىڭىزنىڭ ۋاقتى ئۆتۈپ كىتىپتۇ ، قايتا تىزىملىتىپ مەشخۇلات قىلغايسىز',
                'zh'=>'Token 已过期，请前往登录页面重新登录!'
            ];
            return Fail($message[$lang]);
        }
        $data = [
            "Message"=>$e->getMessage(),
            "File"=>$e->getFile(),
            "Line"=>$e->getLine()
        ];
        $statusCode = 0;
        $message = $e->getMessage();
        try {
            $statusCode =$e->getStatusCode();
        }
        catch (\Throwable $error2){
            $statusCode = $e->getCode();
        }

        if($statusCode === 404) {
            Artisan::call('optimize');
            if ($request->header('lang') === 'ug'){
                $error_message = 'بۇ ئادرىس مۇلازىمىتىر مۇلازىمەت دائىرىسىدە ئەمەس';
            }
            else{
                $error_message = __("http-statuses.404");
            }
            if($request->is('api/*')){

                return Fail($error_message,null,404);
            }
            return response()->view('404', [
                'code'=>404,
                'message'=>$error_message
            ]);
        }

        if($request->is('api/*')){
            if($statusCode === 0){
                return Fail($message,null,$statusCode,$data);
            }
            else if($statusCode === 888)
            {
                return Fail($message,null,$statusCode,null);
            }
            try {
                $message = trans("http-statuses.{$statusCode}");
            }
            catch (Throwable $error3){
                $message =__('auth.web_status_code_error');
            }
            return Fail($message,null,$statusCode,$data);
        }
        else{
            try {
                if ($this->isHttpException($e)) {
                    Artisan::call('optimize');
                    return response()->view('404', [
                        'code'=>(int)$e->$statusCode,
                        'message'=>__("http-statuses.{$statusCode}")
                    ]);
                }
            }catch (Throwable $error4){}

            return parent::render($request, $e);
        }
    }
}
